package demo.ClassLoad;

import java.lang.reflect.Method;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/5-08-05-14:48
 * @Description：demo.ClassLoad
 */
public class TestUserAdd {
    public static void main(String[] args) throws Exception {

        //3、反射调用方法
        exception(UserAddServlet.class,"/sho");
    }
    public static void exception(Class c, String urli) throws Exception {
        String url = "http://localhost:8080/user";
        //1、切割url中的url  /add
        int i = url.lastIndexOf("/");
        boolean flag = false;
        String uri = url.substring(21);
        uri = uri + "/*";
        System.out.println(uri);
        //2、和UserAddServlet上的注解的值比对，如果两者一致
//        Class<UserAddServlet> c = UserAddServlet.class;
//        c.getS
        if(c.isAnnotationPresent(WebServlet.class)){
            WebServlet annotation = (WebServlet) c.getAnnotation(WebServlet.class);
            if(uri.equals(annotation.value())){
                System.out.println("欢迎进入用户界面");
                Method[] methods = c.getDeclaredMethods();
                for (Method method : methods) {
                    if(method.getName().equals(urli.substring(1))){
                        Method service = c.getMethod("service",String.class);
                        System.out.println(method.getName());
                        service.invoke(c.newInstance(),method.getName());
                        flag = true;
                        break;
                    }
                }
//                Method service = c.getMethod("service");
//                service.invoke(c.newInstance(),null);
//                c.getDeclaredMethod("doGet");
            }
            if(!flag){
                System.out.println("方法不存在！");
            }
        }else {
            System.out.println("该方法不存在！");
        }
    }
}
